// fast4j - Fast & Agile Service Tools for Java
// Copyright (C) 2007 Alexandre ROMAN
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

// $Id: ServiceContextInterceptor.java 36 2007-03-27 22:02:40Z alexandre.roman $

package service.util;

import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import service.api.ServiceContext;
import service.api.ServiceContextHolder;
import fast4j.ejbbridge.ServiceBridgeContextHolder;

/**
 * Service context handler. This method intercepts a service call, and logs the
 * attached {@link ServiceContext} instance.
 * @author alexandre.roman
 */
public class ServiceContextInterceptor {
    private final Logger log = LoggerFactory.getLogger(getClass());
    
    @SuppressWarnings("unchecked")
    public Object intercept(ProceedingJoinPoint jp) throws Throwable {
        final String serviceContextKey = "serviceContext";
        
        final ServiceContext client = (ServiceContext) ServiceBridgeContextHolder
                .get().get(serviceContextKey);
        if (client == null) {
            log.warn("No ServiceContext was provided");
        } else {
            // get the context from the client request
            log.debug("ServiceContext before invocation: {}", client);
            ServiceContextHolder.get().copyFrom(client);
        }
        
        try {
            // call and return result from method
            return jp.proceed();
        } finally {
            if (client != null) {
                log.debug("ServiceContext after invocation: "
                        + ServiceContextHolder.get());
                // copy back the context for the client
                ServiceBridgeContextHolder.get().put(serviceContextKey,
                    ServiceContextHolder.get());
                // free resources (very important!)
                ServiceContextHolder.release();
            }
        }
    }
}
